//
//  CorgiStatusPictureView.swift
//  weibo
//
//  Created by Corgi on 17/3/25.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit
import SDWebImage
private let Cell_ID = "Cell_ID"
// 计算cell的间距
let itemMargin: CGFloat = 5
// 计算cell的宽高
let cellWH = (screenWidth - 2*HOMECELLMARGIN - 2*itemMargin)/3

class CorgiStatusPictureView: UICollectionView {

    var picUrls: [CorgiPictureUrlsModel]? {
    
        didSet{
        
            let size = dealPictureViewSize(count: picUrls!.count)
            
            self.snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            
            if picUrls?.count == 1 {
            
                layout.itemSize = size
            } else {
            
                layout.itemSize = CGSize(width: cellWH, height: cellWH)
            
            }
            
            layoutIfNeeded()
            
            reloadData()
        }
    }
    
    private func dealPictureViewSize(count: Int) -> CGSize {
        
        if count == 1 {
        
            if let thumbnail_pic = picUrls?.first?.thumbnail_pic {
            
                let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: thumbnail_pic)
            
                if let img = image {
                
                    var imgW = img.size.width
                    
                    var imgH = img.size.height
                    
                    if imgW < 80 {
                        imgW = 80
                    }
                    
                    if imgH > 150 {
                        imgH = 150
                    }
                    
                    return CGSize(width: imgW, height: imgH)
                }
            }
        }
        
        // 计算行数和列数
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        
        // 计算配图的宽度和长度
        let w = CGFloat(col)*cellWH + CGFloat(col - 1)*itemMargin
        let h = CGFloat(row)*cellWH + CGFloat(row - 1)*itemMargin
        
        return CGSize(width: w, height: h)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        flowLayout.minimumLineSpacing = itemMargin
        
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    private func setupUI() {
        
        backgroundColor = UIColor.clear
        
        dataSource = self
        
        delegate = self
        
        register(CorgiStatusPictureCell.self, forCellWithReuseIdentifier: cell_ID)
        
        self.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 100, height: 100))
        }
    }
}


extension CorgiStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell: CorgiStatusPictureCell = collectionView.dequeueReusableCell(withReuseIdentifier: cell_ID, for: indexPath) as! CorgiStatusPictureCell
        
        cell.pictureUrlModel = picUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let browser = SDPhotoBrowser()
        
        browser.sourceImagesContainerView = self
        
        browser.imageCount = picUrls!.count
        
        browser.currentImageIndex = indexPath.item
        
        browser.delegate = self
        
        browser.show()
    }

}

extension CorgiStatusPictureView: SDPhotoBrowserDelegate {

    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! CorgiStatusPictureCell
        
        return cell.bigImageView.image
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let urlStr = ((self.picUrls![index].thumbnail_pic ?? "") as NSString).replacingOccurrences(of: "thumbnail", with: "bmiddle")
        
        return URL(string: urlStr)
    }

}

class CorgiStatusPictureCell: UICollectionViewCell {

    var pictureUrlModel: CorgiPictureUrlsModel? {
    
        didSet{
        
            bigImageView.corgi_setImage(urlString: pictureUrlModel?.thumbnail_pic, placeholderImageName: "avatar_default_big")
            
            
            if let thumbnail_pic = pictureUrlModel?.thumbnail_pic, thumbnail_pic.hasSuffix(".gif"){
            
                gifImageView.isHidden = false
            
            } else {
            
                gifImageView.isHidden = true
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        
        backgroundColor = UIColor.white
        
        contentView.addSubview(bigImageView)
        contentView.addSubview(gifImageView)
        
        
        
        bigImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        gifImageView.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
        }
    }
    
    lazy var bigImageView: UIImageView = {
    
        let img = UIImageView(imageName: "avatar_default_big")
        
        img.contentMode = .scaleAspectFill
        
        img.clipsToBounds = true
    
        return img
    }()
    
    private lazy var gifImageView: UIImageView = UIImageView(imageName: "timeline_image_gif")
}

